package com.hitqz.robot.biz.flow.component.agv;

import com.alibaba.fastjson.JSONObject;
import com.google.common.collect.Lists;
import com.google.common.collect.Maps;
import com.hitqz.robot.api.business.dto.GoodsBufferDetailDto;
import com.hitqz.robot.api.business.dto.GoodsBufferDto;
import com.hitqz.robot.api.business.model.dto.FlowContextDto;
import com.hitqz.robot.api.business.model.dto.FlowPatrolPreAndEndTicketsDto;
import com.hitqz.robot.api.common.entity.Robot;
import com.hitqz.robot.api.common.entity.Tickets;
import com.hitqz.robot.api.common.entity.TicketsTask;
import com.hitqz.robot.biz.flow.util.LiteFlowUtil;
import com.hitqz.robot.biz.service.RobotMapPosService;
import com.hitqz.robot.biz.service.RobotService;
import com.hitqz.robot.biz.service.TicketsService;
import com.hitqz.robot.common.core.util.R;
import com.hitqz.robot.driver.parent.RobotDriverService;
import com.yomahub.liteflow.annotation.LiteflowComponent;
import com.yomahub.liteflow.core.NodeComponent;
import lombok.AllArgsConstructor;
import lombok.extern.slf4j.Slf4j;
import org.springframework.http.HttpEntity;
import org.springframework.http.HttpHeaders;
import org.springframework.http.MediaType;
import org.springframework.web.client.RestTemplate;

import java.util.List;
import java.util.Map;
import java.util.Optional;

/**
 * @author xupkun
 * @date 2025/4/25
 */
@Slf4j
@LiteflowComponent(value = "QianfuAgvPut", name = "[轮对/轮轴]潜伏车换料")
@AllArgsConstructor
public class QianfuAgvPut extends NodeComponent {

    private final RobotDriverService robotDriverService;

    private final TicketsService ticketsService;

    private final RobotService robotService;


    private static final String baseUrl = "http://127.0.0.1:8900/api/fms";

    private static final String addTask = baseUrl + "/addTask";

    private final RestTemplate restTemplate;

    private final RobotMapPosService robotMapPosService;

    private static final String getTaskStatus = "http://localhost:9999/admin/km/agv/goodsStatusByGroup/15";

    @Override
    public void process() throws Exception {

        LiteFlowUtil.checkInterruptFlag();
        FlowContextDto dto =  this.getRequestData();
        TicketsTask task = dto.getTicketsTask();
        log.info("潜伏车的任务数据 {}", task.getParseOrderParams());
        Robot robot = robotService.getDefaultRobot();
        FlowPatrolPreAndEndTicketsDto ticketsDto = JSONObject.parseObject(dto.getTicketsTask()
                .getParseOrderParams(), FlowPatrolPreAndEndTicketsDto.class);
        String targetPosName = Optional.ofNullable(ticketsDto.getModalData().get("targetPosName"))
                .orElse(ticketsDto.getModalData().get("targetPosCode")).toString();
        String[] targetPos = targetPosName.split(",");
        String targetPos1 = targetPos[0];
        String targetPos2 = targetPos[0];
        //log.info("潜伏车的位置：{}-{}", targetPos1, targetPos2);
        // 分割开的 第一个是左边 第二个是右边
        //
        String leftEmpty = "", changeLeftFull = "",  rightEmpty="", changeRightFull="";

        R groupBuffers = restTemplate.getForObject(getTaskStatus, R.class);

        log.info("获取到的缓存架的数据为:{}", JSONObject.toJSONString(groupBuffers));
        //第一个满托盘位置 5243,5244-南   5241,5242-北
        GoodsBufferDto bufferDto = JSONObject.parseObject(JSONObject.toJSONString(groupBuffers.getData()), GoodsBufferDto.class);
        List<GoodsBufferDetailDto> data =bufferDto.getDtoList();
        List<GoodsBufferDetailDto> reData = Lists.reverse(data);

        leftEmpty = data.stream().filter(t-> t.getStoreStatus() == 1).findFirst().get().getBindPosName();

        String finalLeftEmpty = leftEmpty;


        rightEmpty = targetPos1.equals("5243") ?
                reData.stream().filter(t-> t.getStoreStatus() == 1 && !t.getBindPosName().equals(finalLeftEmpty) ).findFirst().get().getBindPosName()
                : data.stream().filter(t-> t.getStoreStatus() == 1 && !t.getBindPosName().equals(finalLeftEmpty)).findFirst().get().getBindPosName();

        changeLeftFull = targetPos1.equals("5243") ?
                data.stream().filter(t-> t.getStoreStatus() == 4
                    && t.getStoreName().equals("70-left")
                ).findFirst().get().getBindPosName() :
                data.stream().filter(t-> t.getStoreStatus() == 4
                    && t.getStoreName().equals("60-left")
                ).findFirst().get().getBindPosName() ;

        changeRightFull = targetPos1.equals("5243") ?
                reData.stream().filter(t-> t.getStoreStatus() == 4 &&
                        t.getStoreName().equals("70-right")).findFirst().get().getBindPosName()
                : data.stream().filter(t-> t.getStoreStatus() == 4
                && t.getStoreName().equals("60-right")
        ).findFirst().get().getBindPosName();

        Tickets tickets =  ticketsService.getById(task.getTicketsId());
        //Tickets tickets =  ticketsService.getById(1);
        String taskName = tickets.getName().split("--")[0];
        String taskNo = taskName + System.currentTimeMillis();
        Map<String, Object> requestParams = Maps.newHashMap();
        requestParams.put("TaskNo", taskNo);
        requestParams.put("Priority", 0);
        requestParams.put("VehicleNo", robot.getRobotSn());
        requestParams.put("FinishAction", 0);
        requestParams.put("TaskType", taskName);

        //requestParams.put("leftFull", leftFull);
        requestParams.put("leftEmpty", leftEmpty);
        requestParams.put("changeLeftFull", changeLeftFull);
        //requestParams.put("rightFull", rightFull);
        requestParams.put("rightEmpty", rightEmpty);
        requestParams.put("changeRightFull", changeRightFull);
        String requestBody = JSONObject.toJSONString(requestParams);
        sendDispatch(requestBody, addTask);


        // 读取变量 rep_next_step 1


        // 读取变量 rep_next_step 2

        // 读取变量 rep_next_step 3


        // 读取变量 rep_next_step 4







    }



    private String sendDispatch(String requestBody, String uri) {
        try {
            HttpHeaders headers = new HttpHeaders();
            headers.setContentType(MediaType.APPLICATION_JSON);
            HttpEntity<String> requestEntity = new HttpEntity<>( requestBody, headers);
            log.info("请求地址{} 参数: {}", uri
                    , requestBody);
            String response = restTemplate.postForObject(uri, requestEntity, String.class);
            log.info("任务返回接果: " + response);
            return response;
        } catch (Exception e) {
            log.info("请求地址发生异常:" + e.getMessage());
        }
        return null;
    }
}
